<?php

class OrderController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/view';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update', 'step1', 'step2', 'step3', 'step4', 'finish', 'cancel', 'list', 'detail', 'pay', 'result'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Order;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Order']))
		{
			$model->attributes=$_POST['Order'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Order']))
		{
			$model->attributes=$_POST['Order'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

    function getDateDiff($date1, $date2)
    {
        $date1_arr = explode("-",$date1);
        $date2_arr = explode("-",$date2);
        $day1 = mktime(0,0,0,$date1_arr[1],$date1_arr[2],$date1_arr[0]);
        $day2 = mktime(0,0,0,$date2_arr[1],$date2_arr[2],$date2_arr[0]);
        $days = round(($day2 - $day1)/3600/24);
        return $days;
    }

	/**
	 * Lists all models.
	 */
	public function actionStep1()
	{
		$this->layout = '//layouts/view_order';
		$this->setOrderProp();
		$this->render('step1');
	}

    function setOrderProp()
    {
        if (!empty($_POST["in_date"]))
        	$_SESSION["in_date"] = $_POST["in_date"];
        if (!empty($_POST["out_date"]))
        	$_SESSION["out_date"] = $_POST["out_date"];
        if (!empty($_POST["room_type"]))
        	$_SESSION["room_type"] = $_POST["room_type"];
        if (!empty($_POST["room_count"]))
        	$_SESSION["room_count"] = $_POST["room_count"];
        if (!empty($_POST["bed_type"]))
        	$_SESSION["bed_type"] = $_POST["bed_type"];
        if (!empty($_POST["other"]))
        	$_SESSION["other"] = $_POST["other"];
        if (!empty($_POST["add_bed"]))
        	$_SESSION["add_bed"] = $_POST["add_bed"];
        if (!empty($_POST["r_msg"]))
        	$_SESSION["r_msg"] = $_POST["r_msg"];
        if (!empty($_POST["r_email"]))
        	$_SESSION["r_email"] = $_POST["r_email"];
        if (!empty($_POST["rdoMember"]))
        {
        	$memType = $_POST["rdoMember"];
        	$_SESSION["member_type"] = $memType;
        	if ($memType === 'old')
        	{
        		$userInfo = User::model()->findByAttributes(array('user_name'=>Yii::app()->user->getState('userName')));
        		$_SESSION["link_name"] = $userInfo->name;
        		$_SESSION["link_email"] = $userInfo->email;
        		$_SESSION["link_gender"] = $userInfo->gender;
        		$_SESSION["link_mobile"] = $userInfo->mobile;
        		$_SESSION["link_id_card"] = $userInfo->id_card;
        		$_SESSION["link_address"] = $userInfo->address;
        	}
        	else if ($memType === 'new')
        	{
        		if (!empty($_POST["link_name"]))
        			$_SESSION["link_name"] = $_POST["link_name"];
        		if (!empty($_POST["link_email"]))
        			$_SESSION["link_email"] = $_POST["link_email"];
        		if (!empty($_POST["link_gender"]))
        			$_SESSION["link_gender"] = $_POST["link_gender"];
        		if (!empty($_POST["link_mobile"]))
        			$_SESSION["link_mobile"] = $_POST["link_mobile"];
        		if (!empty($_POST["link_id_card"]))
        			$_SESSION["link_id_card"] = $_POST["link_id_card"];
        		if (!empty($_POST["link_address"]))
        			$_SESSION["link_address"] = $_POST["link_address"];
        		if (!empty($_POST["link_desc"]))
        			$_SESSION["link_desc"] = $_POST["link_desc"];
        	}
        }
    }
    
    public function actionStep4()
    {
		$this->layout = '//layouts/view_order';
    	$this->setOrderProp();
    	if (empty($_POST["rdoMember"]) || empty($_SESSION["link_name"]) || empty($_SESSION["link_email"]) || empty($_SESSION["link_mobile"])
        	|| empty($_SESSION["link_id_card"]) || empty($_SESSION["link_gender"]) || empty($_SESSION["link_address"]))
    	{
    		$this->actionStep3();
    		exit();
    	}
    	$this->render('step4');
    }
    
    public function actionStep3()
    {
		$this->layout = '//layouts/view_order';
    	$this->setOrderProp();
    	if (empty($_SESSION["bed_type"]))
    	{
    		$this->actionStep2();
    		exit();
    	}
    	if (!empty($_SESSION["add_bed"]) && $_SESSION["add_bed"] === "1")
    	{
    		$_SESSION["price"] = floatval($_SESSION["price"]) + intval($_SESSION["room_count"]) * 300;
    	}
    	$userInfo = User::model()->findByAttributes(array('user_name'=>Yii::app()->user->getState('userName')));
    	$this->render('step3', array(
    		'userInfo'=>$userInfo
    	));
    }
	
	public function actionStep2()
	{
		$this->layout = '//layouts/view_order';
		$this->setOrderProp();
		if (empty($_SESSION["in_date"]) || empty($_SESSION["out_date"]) || empty($_SESSION["room_type"]))
		{
			$this->render('step1');
            exit();
		}
        $days = intval($this->getDateDiff($_SESSION["in_date"], $_SESSION["out_date"])) + 1;
		$roomSurplus = new CActiveDataProvider('RoomSurplus', array(
			'criteria'=>array(
				'condition'=>'room_id='.$_SESSION["room_type"].' and sur_date >= "'
                    .$_SESSION["in_date"].'" and sur_date <= "'.$_SESSION["out_date"].'"'
			),
			'pagination'=>array(
				'pageSize'=>100
			)
		));
		$roomInfo = Room::model()->findByAttributes(array('id'=>$_SESSION["room_type"]));
		$_SESSION["room_type_name"] = $roomInfo->name;
		$surplusInfo = RoomSurplus::model()->findByAttributes(array('room_id'=>$_SESSION["room_type"], 'sur_date'=>date('Y-m-d')));
		$canOrder = 'yes';
        if (count($roomSurplus->getData()) < $days)
        {
            $canOrder = 'no';
        }
        else
        {
            foreach ($roomSurplus->getData() as $key=>$value)
            {
                if ($value->surplus_count == 0)
                {
                    $canOrder = 'no';
                    break;
                }
            }
        }
        if ($canOrder == 'yes')
        {
        	$totalCount = 0;
        	foreach ($roomSurplus->getData() as $key=>$value)
        	{
        		$totalCount += $value["discount_price"];
        	}
        	$totalCount = $totalCount * intval($_SESSION["room_type"]);
        	$_SESSION["price"] = $totalCount;
        }

        $this->render('step2', array(
			'roomSurplus'=>$roomSurplus->getData(),
			'roomInfo'=>$roomInfo,
			'surplusInfo'=>$surplusInfo,
            'canOrder'=>$canOrder
		));
	}
	
	public function actionFinish()
	{
		$this->layout = '//layouts/view';
		$order = new Order();
		$order->submit_time = date('Y-m-d H:i:s');
		$order->room_id = $_SESSION["room_type"];
		$order->price = $_SESSION["price"];
		$order->in_date = $_SESSION["in_date"];
		$order->out_date = $_SESSION["out_date"];
		$order->order_type = "1";
		$order->bed_type = $_SESSION["bed_type"];
		if (!empty($_SESSION["other"]))
			$order->other = $_SESSION["other"];
		$order->user_id = Yii::app()->user->getState('userId');
		$order->room_name = $_SESSION["room_type_name"];
		$order->room_count = $_SESSION["room_count"];
		if (!empty($_SESSION["add_bed"]))
			$order->add_bed = $_SESSION["add_bed"];
		if (!empty($_SESSION["r_msg"]))
			$order->r_msg = $_SESSION["r_msg"];
		else 
			$order->r_msg = 0;
		if (!empty($_SESSION["r_email"]))
			$order->r_email = $_SESSION["r_email"];
		else 
			$order->r_email = 0;
		$order->link_name = $_SESSION["link_name"];
		$order->link_gender = $_SESSION["link_gender"];
		$order->link_mobile = $_SESSION["link_mobile"];
		$order->link_id_card = $_SESSION["link_id_card"];
		$order->link_address = $_SESSION["link_address"];
		$order->link_email = $_SESSION["link_email"];
		if (!empty($_SESSION["link_desc"]))
			$order->link_desc = $_SESSION["link_desc"];
		$order->order_no = date('YmdHis'). strval(mt_rand(100, 999));
		
		$order->status = 1;
        $days = intval($this->getDateDiff($_SESSION["in_date"], $_SESSION["out_date"])) + 1;
        
		$roomSurplus = new CActiveDataProvider('RoomSurplus', array(
			'criteria'=>array(
				'condition'=>'room_id='.$_SESSION["room_type"].' and sur_date >= "'
                    .$_SESSION["in_date"].'" and sur_date <= "'.$_SESSION["out_date"].'"'
			),
			'pagination'=>array(
				'pageSize'=>100
			)
		));
		$list = $roomSurplus->getData();
		if (!empty($list) && count($list) == $days)
		{
			foreach ($list as $key => $value) {
				if ($value->surplus_count < $order->room_count)
				{
					echo '<script type="text/javascript">alert("预订失败！");</script>';
					exit();
				}
				else 
				{
					$value->surplus_count = $value->surplus_count - $order->room_count;
					if ($value->surplus_count < 0)
					{
						echo '<script type="text/javascript">alert("预订失败！");</script>';
						exit();
					}
				}
			}
			$transaction=Yii::app()->db->beginTransaction();
			try {
				foreach ($list as $key => $value) {
					if (!$value->save())
					{
						throw new Exception();
					}
				}
				if (!$order->save())
				{
					throw new Exception();
				}
				$transaction->commit();
				unset($_SESSION["sumwers"]);
				unset($_SESSION["room_type"]);
				unset($_SESSION["price"]);
				unset($_SESSION["in_date"]);
				unset($_SESSION["out_date"]);
				unset($_SESSION["bed_type"]);
				unset($_SESSION["other"]);
				unset($_SESSION["room_type_name"]);
				unset($_SESSION["room_count"]);
				unset($_SESSION["add_bed"]);
				unset($_SESSION["r_msg"]);
				unset($_SESSION["r_email"]);
				unset($_SESSION["link_name"]);
				unset($_SESSION["link_gender"]);
				unset($_SESSION["link_mobile"]);
				unset($_SESSION["link_id_card"]);
				unset($_SESSION["link_address"]);
				unset($_SESSION["link_email"]);
				unset($_SESSION["link_desc"]);
				$this->redirect('?r=order/list');
			} catch (Exception $e) {
				$transaction->rollback();
				echo '<script type="text/javascript">alert("预订失败！");</script>';
				print_r($order->getErrors());
			}
		}
		else
		{
			echo '<script type="text/javascript">alert("预订失败！");</script>';
		}
	}
	
	public function actionCancel($id)
	{
		$order = Order::model()->findByAttributes(array('id'=>$id));
		if (!empty($order))
		{
			if ($order->status != 1)
			{
				echo '<script type="text/javascript">alert("该订单不在等待付款状态，不能取消！");location.href = "?r=user/order";</script>';
			}
			else
			{
				$order->status = 0;
				$roomSurplus = new CActiveDataProvider('RoomSurplus', array(
						'criteria'=>array(
								'condition'=>'room_id='.$order->room_id.' and sur_date >= "'
								.$order->in_date.'" and sur_date <= "'.$order->out_date.'"'
						),
						'pagination'=>array(
								'pageSize'=>100
						)
				));
				$transaction=Yii::app()->db->beginTransaction();
				try 
				{
					foreach ($roomSurplus->getData() as $key => $value)
					{
						$value->surplus_count += $order->room_count;
						if (!$value->save())
							throw new Exception();
					}
					if (!$order->save())
						throw new Exception();
					$transaction->commit();
				} 
				catch (Exception $e) 
				{
					$transaction->rollback();
					echo '<script type="text/javascript">alert("订单取消失败！");location.href = "?r=order/list";</script>';
				}
				
				echo '<script type="text/javascript">alert("取消成功！");location.href = "?r=order/list";</script>';
			}
		}
		else
		{
			echo '<script type="text/javascript">alert("取消失败，该订单已不存在！");location.href = "?r=order/list";</script>';
		}
	}
	
	public function actionList()
	{
		$this->layout = '//layouts/view';
		$orderList = new CActiveDataProvider('Order', array(
				'criteria'=>array(
						'condition'=>'user_id='.Yii::app()->user->getState('userId')
				),
				'pagination'=>array(
						'pageSize'=>100
				)
		));
	
		$this->render('list', array(
				'orderList'=>$orderList->getData()
		));
	}

	public function actionDetail($id)
	{
		$this->layout = '//layouts/view';
		$order = Order::model()->findByAttributes(array('id'=>$id));
		$this->render('detail', array(
			'order'=>$order
		));
	}
	
	function make_seed()
	{
		list($usec, $sec) = explode(' ', microtime());
		return (float) $sec + ((float) $usec * 100000);
	}
	
	public function actionPay($id)
	{
		$order = Order::model()->findByAttributes(array('id'=>$id));
		mt_srand($this->make_seed());
		
		$parameter['transType']         = '01';	//消费
		$parameter["merAbbr"]			= '青城豪生国际酒店';	//商户名称
		//$parameter["merId"]			= '';	//商户编号
		$parameter["acqCode"]			= '';	//收单机构代码
		//交易流水号
		//$parameter["qid"]				= '';
		//系统跟踪号
		//$parameter["traceNumber"]		= '';
		//系统跟踪时间
		//$parameter["traceTime"]		= '';
		//上一笔交易的流水号
		$parameter['origQid']           = '';
		//商品地址
		$parameter['commodityUrl']      = "http://127.0.0.1/hs?r=room";
		//商品名称
		$parameter['commodityName']     = '酒店客房';
		//商品单价
		$parameter['commodityUnitPrice'] = 221000;
		//商品数量
		$parameter['commodityQuantity'] = 1;
		//商品折扣
		$parameter['commodityDiscount'] = 0;
		//运输费用
		$parameter['transferFee']       = 1000;
		//订单号
		$parameter['orderNumber']       = $order->order_no;
		//交易金额
		$parameter['orderAmount']       = intval($order->price * 100);
		//币种
		$parameter['orderCurrency']     = '156';
		//交易发生时间
		$parameter['orderTime']         = date('YmdHis');	
		//交易完成时间
		//$parameter['respTime']		= '';
		//持卡人IP
		$parameter['customerIp']        = '172.17.136.34';
		//挂卡人姓名
		$parameter['customerName']      = '周恩亚';
		//默认支付方式
		$parameter['defaultPayType']    = '';
		//默认银行编码
		$parameter['defaultBankNumber'] = '';
		//交易超时时间-毫秒
		$parameter['transTimeout']      = '300000';
		$parameter['merReserved']       = '';
		//前台通知URL
		$parameter['frontEndUrl']       = "http://127.0.0.1/hs/pay/front_result.php";
		//后台通知URL
		$parameter['backEndUrl']        = "http://127.0.0.1/hs/pay/front_result2.php";
		
		$pay_service = new quickpay_service($parameter);
		$html = $pay_service->create_html();
		
		//var_dump($html);
		echo $html;
	}
	
	public function actionResult()
	{
		$orderPay = new OrderPay();
		$orderPay->order_no = $_POST["orderNumber"];
		$orderPay->order_amount = intval($_POST["orderAmount"]) / 100;
		$orderPay->qid = $_POST["qid"];
		$orderPay->pay_time = $_POST["respTime"];
		$orderPay->trace_no = $_POST["traceNumber"];
		$orderPay->trace_time = $_POST["traceTime"];
		$orderPay->settle_amount = intval($_POST["settleAmount"]) / 100;
		$orderPay->pay_type = $_POST["pay_type"];
		$order = Order::model()->findByAttributes(array('order_no'=>$orderPay->order_no));
		$order->status = 2;
		$result = 'yes';
		
		$transaction=Yii::app()->db->beginTransaction();
		try
		{
			if (!$orderPay->save() || !$order->save())
			{
				$result = 'no';
				throw new Exception();
			}
			$transaction->commit();
			//发送通知短信
			//发送通知邮件
		}
		catch (Exception $e)
		{
			$result = 'no';
			$transaction->rollback();
		}
		
		$this->render('result', array(
			'result'=>$result
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Order('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Order']))
			$model->attributes=$_GET['Order'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Order the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Order::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Order $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='order-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
